//定义js命名空间
Ext.namespace('FsCarInfo.FsGateinfo');
//DateTime -- date , decimal -- float
// { name: 'Department.Name', mapping: 'Department.Name' },
// { name: 'Department'},
//FsGateinfo FieldArray
FsCarInfo.FsGateinfo.BaseFieldsArray = new Array(
	{ name: 'Id', type: 'string' },
	{ name: 'Name', type: 'string' },
	{ name: 'Code', type: 'string' },
	{ name: 'Type', type: 'string' },
	{ name: 'Ip', type: 'string' },
	{ name: 'Mac', type: 'string' },
	{ name: 'InAreaId', type: 'string' },
	{ name: 'OutAreaId', type: 'string' },
	{ name: 'State', type: 'string' },
	{ name: 'Description', type: 'string' },
	{ name: 'Createtime', type: 'date' },
	{ name: 'Isdelete', type: 'bool' },
	{ name: 'Version', type: 'int' },
	{ name: 'InArea.Name', mapping: 'InArea.Name' },
	{ name: 'OutArea.Name', mapping: 'OutArea.Name' }
);

//FsGateinfo JsonReader
FsCarInfo.FsGateinfo.JsonReader = new Ext.data.JsonReader({
	root: 'data'
}, FsCarInfo.FsGateinfo.BaseFieldsArray);

//FsGateinfo JsonStore
FsCarInfo.FsGateinfo.JsonStore = Ext.extend(Infrastructure.BaseJsonStore, {
	constructor: function (cfg) {
		cfg = cfg || {};
		FsCarInfo.FsGateinfo.JsonStore.superclass.constructor.call(this, Ext.apply({
			url: '/FsGateinfo/GetPlist',
			params: {
				start: 0,
				limit: ALL_PAGESIZE_SETTING
			},
			remoteSort: true,
			fields: FsCarInfo.FsGateinfo.BaseFieldsArray,
			listeners: {
				'remove': function (thiz, record, index) {
					Ext.Ajax.request({
						url: '/FsGateinfo/Delete?Id=' + record.data.Id,
						success: function (response, opts) {
							var result = Ext.util.JSON.decode(response.responseText);
							if (result.success == false) {
								JsHelper.ShowError(result.msg);
								this.insert(0, record);
							}
						}
					});
				}
			}
		}, cfg));
	}
});

//FsGateinfo GridPanel
FsCarInfo.FsGateinfo.GridPanel = Ext.extend(Ext.grid.GridPanel, {
	// User property
	//基本处理Url
	baseUrl: '/FsGateinfo/',
	//提交保存Url
	formSubmitUrl: '/FsGateinfo/SaveOrUpdate',
	//提交保存提示信息
	formSubmitMsg: '确定要保存吗?',
	//工具栏标签
	tbarMask: '0',
	//表格列默认显示
	columnMask: '012345600001230000090123000000',
	//状态
	itemState: '',

	// Property
	stripeRows: true,
	frame: true,
	border: true,
	layout: 'fit',
	loadMask: true,
	enableColumnMove: false,
	viewConfig: {
		autoFill: true
	},
	store: new FsCarInfo.FsGateinfo.JsonStore(),
	//stateful: true,
	//stateId: 'FsCarInfo.FsGateinfo.GridPanel',

	//constructor
	initComponent: function () {
		
		var itemGrid = this;
		var tbarMask = this.tbarMask;
		var colMask = this.columnMask;
		var cmdAddEntity = this.onAddEntity;
		var cmdDeleteEntity = this.onDeleteEntity;
		var cmdLoadEntity = this.onLoadEntity;
		var cmdQueryList = this.onQueryList;
		//提交审批
		var cmdTbarCmd = function () {
			this.tbarSubmit(this.baseUrl + 'MethodName', '确定要提交吗?', '您的信息提交到系统..');
		};
		//set store params
		this.store.setBaseParam('state', this.itemState);

		// The filter.
		var gridFilter = new Ext.ux.grid.GridFilters({
			encode: true,
			filters: [
				{ dataIndex: 'Name', type: 'string' },
				{ dataIndex: 'Type', type: 'list', options: JsHelper.GetFilterListData(FsCarInfo.Params.Gate_TypeStore.data.items, 'Code', 'Name') },
				{ dataIndex: 'Ip', type: 'string' },
				{ dataIndex: 'Mac', type: 'string' },
				{ dataIndex: 'State', type: 'list', options: JsHelper.GetFilterListData(Infrastructure.Params.StateStore.data.items, 'Code', 'Name') },
				{ dataIndex: 'Createtime', type: 'date' }
			]
		});

		// selModel
		var selModel = new Ext.grid.CheckboxSelectionModel({
			//header: '',
			//singleSelect: true,
			listeners: {
				'selectionchange': function (sm) {
					// 控制工具栏按钮是否可用
					itemGrid.delBtn.setDisabled(sm.getCount() < 1);
				}
			}
		});

		// columnModel 对于不常需要显示的 hidden: true 
		var gridColumn = new Ext.grid.ColumnModel({
			columns: [
				new Ext.grid.RowNumberer(),
				selModel,
				{ header: '名称', dataIndex: 'Name' },
				{ header: '出闸区域', dataIndex: 'OutArea.Name' },
				{ header: '入闸区域', dataIndex: 'InArea.Name' },
				{ header: 'IP', dataIndex: 'Ip' },
				{ header: 'MAC', dataIndex: 'Mac' },
				{ header: '状态', dataIndex: 'State',
					renderer: function (v) {
						return v == '' ? '' : Infrastructure.Params.StateStore.getById(v).get('Name');
					}
				}
			]
		});

		// PageBar
		var pagebBar = new Infrastructure.BasePagingToolbar({
			store: this.store,
			plugins: this.plugins
		});

		// 常用工具栏
		var toolBar = [{
			xtype: 'tbaraddbtn',
			hidden: tbarMask.substring(0, 1) != '1',
			handler: cmdAddEntity,
			scope: itemGrid
		}, {
			hidden: tbarMask.substring(0, 1) != '1',
			xtype: 'tbseparator'
		}, {
			xtype: 'tbardelbtn',
			hidden: tbarMask.substring(0, 1) != '1',
			handler: cmdDeleteEntity,
			scope: itemGrid
		}, '-'];

		Ext.apply(this, {
			plugins: [gridFilter],
			sm: selModel,
			cm: gridColumn,
			tbar: toolBar,
			bbar: pagebBar,
			listeners: {
				'rowdblclick': cmdLoadEntity
			}
		});

		FsCarInfo.FsGateinfo.GridPanel.superclass.initComponent.call(this);
	},

	/****************** 
	* user function 
	******************/

	// 添加
	onAddEntity: function () {
		var itemGrid = this;
		var itemEditForm = new FsCarInfo.FsGateinfo.EditForm({
			listeners: {
				'afterSave': function (ele, rt) {
					if (rt) {
						ele.form.reset();
						var itemGridStore = itemGrid.store;
						itemGridStore.reload();
						JsHelper.ShowInfo('添加信息成功!');
					}
				}
			}
		});
		var itemEditWin = new FsCarInfo.FsGateinfo.EditWin({
			items: [itemEditForm]
		});
		itemEditWin.show();
	},

	// 读取信息显示
	onLoadEntity: function () {
		var itemGrid = this;
		var selRecord = this.getSelectionModel().getSelected();
		if (selRecord == null) {
			JsHelper.ShowError('请选择记录编辑..');
			return -1;
		}
		var selId = selRecord.data.Id;
		// formReader
		var formReader = new Ext.data.JsonReader({
			root: 'data'
		}, FsCarInfo.FsGateinfo.BaseFieldsArray);
		// form
		var itemEditForm = new FsCarInfo.FsGateinfo.EditForm({
			dataId: selId,
			dataRecord: selRecord,
			submitUrl: this.formSubmitUrl,
			submitMsg: this.formSubmitMsg,
			waitMsg: '数据加载中...',
			reader: formReader,
			listeners: {
				'afterSave': function (ele, rt) {
					if (rt) {
						itemGrid.store.reload();
						JsHelper.ShowInfo('信息更新成功!');
					}
				}
			}
		});
		var itemEditWin = new FsCarInfo.FsGateinfo.EditWin({
			items: [itemEditForm]
		});
		itemEditWin.show();
		
		//itemEditForm.form.reader = itemEditForm.reader;
		var formLoadArgs = {
			url: '/FsGateinfo/GetById',
			params: {
				'Id': selId
			},
			waitMsg: '数据加载中...'
		};

		itemEditForm.getForm().load(formLoadArgs);

		//itemEditForm.form.loadRecord(selRecord);
	},

	// 删除
	onDeleteEntity: function () {
		var itemGrid = this;
		var itemGridStore = this.store;
		JsHelper.DelConfirm(function (btn) {
			if (btn == 'yes') {
				var s = itemGrid.getSelectionModel().getSelections();
				for (var i = 0, r; r = s[i]; i++) {
					itemGridStore.remove(r);
				}
			}
		});
	},

	// 查询
	onQueryList: function () {
		var itemGrid = this;
		var q_query = Ext.getCmp('q_query').getValue();
		itemGrid.store.load({
			params: {
				start: 0,
				limit: ALL_PAGESIZE_SETTING,
				q_query: q_query
			}
		})
	},

	// 提交选定记录..
	tbarSubmit: function (submitUrl, confirmMsg, successMsg) {
		var itemGrid = this;
		var selRecord = this.getSelectionModel().getSelected();
		if (selRecord == null) {
			JsHelper.ShowError('未选择记录.');
			return -1;
		}
		var selId = selRecord.data.Id;
		JsHelper.Confirm(confirmMsg, function (btn) {
			if (btn == 'yes') {
				var ids = [];
				var s = itemGrid.getSelectionModel().getSelections();
				for (var i = 0, r; r = s[i]; i++) {
					ids.push(r.data.Id);
				}
				//加载进度条
				Ext.MessageBox.show({
					msg: '正在提交数据到中心服务器...',
					progressText: '保存数据...',
					width: 300,
					wait: true,
					waitConfig: { interval: 1000 }
				});
				Ext.Ajax.request({
					url: submitUrl,
					params: {
						'Ids': ids.toString()
					},
					success: function (response, opts) {
						Ext.MessageBox.hide();
						var result = Ext.util.JSON.decode(response.responseText);
						if (result.success == false) {
							JsHelper.ShowError('操作失败:' + result.msg);
						} else {
							itemGrid.store.reload();
							Ext.Msg.alert('提示,操作成功', '成功。' + successMsg);
						}
					},
					failure: function (form, action) {
						Ext.MessageBox.hide();
						JsHelper.ShowError('系统异常:' + action.result.msg);
					}
				});
			}
		});
	}
});

//FsGateinfo EditForm
FsCarInfo.FsGateinfo.EditForm = Ext.extend(Infrastructure.BaseForm, {
	dataId: null,
	dataRecord: null,
	submitUrl: '/FsGateinfo/SaveOrUpdate',
	submitMsg: '确定要保存吗?',

	initComponent: function () {
		var itemEditForm = this;
		var cmdUpdate = this.onSave;
		var areaStore = new FsCarInfo.FsArea.JsonStore();

		//Form第一列
		// 定义表单列
		var firstColumn = [{
			fieldLabel: "名称",
			width: 150,
			maxLength: 30,
			allowBlank: false,
			xtype: 'textfield',
			name: 'Name'
		}, {
			fieldLabel: "代码",
			width: 150,
			allowBlank: false,
			maxLength: 30,
			xtype: 'textfield',
			name: 'Code'
		}, {
			fieldLabel: "IP",
			width: 150,
			maxLength: 50,
			allowBlank: false,
			xtype: 'textfield',
			name: 'Ip'
		}, {
			fieldLabel: "MAC",
			width: 150,
			maxLength: 50,
			allowBlank: false,
			xtype: 'textfield',
			name: 'Mac'
		}];

		//Form第二列
		var secondColumn = [{
			fieldLabel: "状态",
			width: 150,
			xtype: 'infra_localcombo',
			store: Infrastructure.Params.StateStore,
			hiddenName: 'State'
		}, {
			xtype: 'idccombo',
			fieldLabel: '进场',
			store: areaStore,
			hiddenName: 'InAreaId'
		}, {
			xtype: 'idccombo',
			fieldLabel: '出场',
			store: areaStore,
			hiddenName: 'OutAreaId'
		}];

		//Form单列
		var singleColumn = [{
			xtype: 'textarea',
			fieldLabel: '描述',
			name: 'Description',
			height: 50,
			width: 430
		}];

		areaStore.load();

		Ext.apply(this, {
			items: [{
				layout: 'column',
				// 注意 现在使用的是两列 要是三列或更多
				// 请改变下面的items
				// 并在上面定义每个列的组件集合
				items: [{
					columnWidth: .5,
					bodyStyle: 'padding:1px',
					layout: 'form',
					defaultType: 'textfield',
					items: firstColumn
				}, {
					columnWidth: .5,
					bodyStyle: 'padding:1px',
					layout: 'form',
					defaultType: 'textfield',
					items: secondColumn
				}]
			}, singleColumn],
			buttons: [{
				xtype: 'btnsubmit',
				handler: cmdUpdate,
				hidden: this.submitUrl == '',
				scope: itemEditForm
			}, {
				xtype: 'btncancle',
				handler: function () {
					itemEditForm.ownerCt.destroy();
				}
			}],
			reader: FsCarInfo.FsGateinfo.JsonReader
		});

		FsCarInfo.FsGateinfo.EditForm.superclass.initComponent.call(this);

		//定义保存后执行的事件
		this.addEvents('afterSave');
	},

	/****************** 
	* user function 
	******************/

	//更新保存信息
	onSave: function () {
		var itemForm = this;
		var id = this.dataId;
		var saveUrl = this.submitUrl;
		if (itemForm.getForm().isValid()) {
			JsHelper.Confirm(this.submitMsg, function (btn) {
				if (btn != 'no') {
					itemForm.getForm().submit({
						waitMsg: '正在提交....',
						url: saveUrl,
						params: {
							'Id': (id == null) ? '' : id
						},
						success: function (form, action) {
							//返回结果后触发保存事件
							itemForm.fireEvent('afterSave', itemForm, true);
						},
						failure: function (form, action) {
							JsHelper.ShowError(action.result.msg);
						}
					});
				}
			});
		}
	}
});

//FsGateinfo DetailWin
FsCarInfo.FsGateinfo.EditWin = Ext.extend(Ext.Window, {
	title: '道闸基本信息设置',
	iconCls: 'door_in',
	width: 600,
	resizable: false,
	constrain: true,
	autoHeight: true,
	modal: true,
	closeAction: 'close',
	plain: true,
	buttonAlign: 'center',

	//constructor
	initComponent: function () {
		FsCarInfo.FsGateinfo.EditWin.superclass.initComponent.call(this);
	}
});
